﻿using mozhi.smarterp.BasicData.DataLinkages.Events;
using Mozhi.Abp.Module.DataLinkage;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Guids;
using Volo.Abp.MultiTenancy;

namespace mozhi.smarterp.BasicData.DataLinkages.EventHandlers
{
    public class DataLinkageDeleteEventHandler : IDistributedEventHandler<BasicDataDataLinkageDeleteEvent>,
          ITransientDependency
    {
        private IDataLinkageRepository _repository;
        private ICurrentTenant _currentTenant;

        public DataLinkageDeleteEventHandler(IDataLinkageRepository repository,  ICurrentTenant currentTenant)
        {
            _repository = repository;
            _currentTenant = currentTenant;
        }


        public async Task HandleEventAsync(BasicDataDataLinkageDeleteEvent eventData)
        {
            using (_currentTenant.Change(eventData.TenantId))
            {
                var dataLinkage = (await _repository.GetListAsync(null, eventData.ProviderId, eventData.ConsumerId)).FirstOrDefault();

                //存在就不处理了，实现等幂处理
                if (dataLinkage == null)
                    return;

                await _repository.DeleteAsync(dataLinkage.Id);
            }
        }
    }
}
